package com.k8sops.backend.service;

import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.apis.AppsV1Api;
import io.kubernetes.client.openapi.apis.CustomObjectsApi;
import io.kubernetes.client.openapi.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.util.Map;

import java.util.ArrayList;
import java.util.List;

@Service
public class KubernetesService {

    private final CoreV1Api coreV1Api;
    private final AppsV1Api appsV1Api;
    private final CustomObjectsApi customObjectsApi;

    @Autowired
    public KubernetesService(ApiClient apiClient) {
        this.coreV1Api = new CoreV1Api(apiClient);
        this.appsV1Api = new AppsV1Api(apiClient);
        this.customObjectsApi = new CustomObjectsApi(apiClient);
    }

    /**
     * 获取所有命名空间
     */
    public List<String> getNamespaces() throws ApiException {
        V1NamespaceList namespaceList = coreV1Api.listNamespace(null, null, null, null, null, null, null, null, null, null);
        List<String> namespaces = new ArrayList<>();
        for (V1Namespace namespace : namespaceList.getItems()) {
            namespaces.add(namespace.getMetadata().getName());
        }
        return namespaces;
    }

    /**
     * 获取指定命名空间中的所有Pod
     */
    public List<V1Pod> getPods(String namespace) throws ApiException {
        V1PodList podList = coreV1Api.listNamespacedPod(namespace, null, null, null, null, null, null, null, null, null, null);
        return podList.getItems();
    }

    /**
     * 获取指定命名空间中的所有Deployment
     */
    public List<V1Deployment> getDeployments(String namespace) throws ApiException {
        V1DeploymentList deploymentList = appsV1Api.listNamespacedDeployment(namespace, null, null, null, null, null, null, null, null, null, null);
        return deploymentList.getItems();
    }

    /**
     * 获取指定命名空间中的所有Service
     */
    public List<V1Service> getServices(String namespace) throws ApiException {
        V1ServiceList serviceList = coreV1Api.listNamespacedService(namespace, null, null, null, null, null, null, null, null, null, null);
        return serviceList.getItems();
    }

    /**
     * 获取集群节点信息
     */
    public List<V1Node> getNodes() throws ApiException {
        V1NodeList nodeList = coreV1Api.listNode(null, null, null, null, null, null, null, null, null, null);
        return nodeList.getItems();
    }

    /**
     * 获取Pod详细信息
     */
    public V1Pod getPodDetails(String namespace, String podName) throws ApiException {
        return coreV1Api.readNamespacedPod(podName, namespace, null);
    }

    /**
     * 获取Pod日志
     */
    public String getPodLogs(String namespace, String podName, String containerName) throws ApiException {
        return coreV1Api.readNamespacedPodLog(podName, namespace, containerName, false, false, null, null, false, null, null, false);
    }

    /**
     * 删除Pod
     */
    public Object deletePod(String namespace, String podName) throws ApiException {
        V1DeleteOptions deleteOptions = new V1DeleteOptions();
        return coreV1Api.deleteNamespacedPod(podName, namespace, null, null, null, null, null, deleteOptions);
    }

    /**
     * 检查连接状态
     */
    public boolean checkConnection() {
        try {
            System.out.println("尝试连接K3s集群...");
            V1NamespaceList namespaceList = coreV1Api.listNamespace(null, null, null, null, null, null, null, null, 1, null);
            System.out.println("成功连接K3s集群！命名空间数量: " + namespaceList.getItems().size());
            return true;
        } catch (ApiException e) {
            System.err.println("连接K3s集群失败: " + e.getMessage());
            System.err.println("响应代码: " + e.getCode());
            System.err.println("响应体: " + e.getResponseBody());
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            System.err.println("连接K3s集群时发生未知错误: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 获取所有Helm Releases
     * 注意：这需要Helm operator在集群中安装
     */
    public Object getAllReleases() throws ApiException {
        try {
            System.out.println("尝试获取Helm Releases...");
            
            // 首先尝试使用Helm CRD API
            Object releases = customObjectsApi.listClusterCustomObject(
                "helm.fluxcd.io", // 组 (group)
                "v1", // 版本 (version)
                "helmreleases", // 复数资源名 (plural)
                null, // pretty
                null, // allowWatchBookmarks
                null, // _continue
                null, // fieldSelector
                null, // labelSelector
                null, // limit
                null, // resourceVersion
                null, // resourceVersionMatch
                null, // timeoutSeconds
                false // watch
            );
            
            System.out.println("成功获取Helm Releases");
            return releases;
        } catch (ApiException e) {
            System.err.println("尝试使用Flux Helm Operator API失败，尝试使用Helm v3 API...");
            
            try {
                // 尝试使用Helm v3 secrets
                // Helm v3将release信息存储在secrets中，标签为 owner=helm
                String labelSelector = "owner=helm";
                V1SecretList secrets = coreV1Api.listSecretForAllNamespaces(null, null, null, labelSelector, null, null, null, null, null, null);
                
                System.out.println("成功获取Helm v3 Releases，数量: " + secrets.getItems().size());
                return secrets;
            } catch (ApiException e2) {
                System.err.println("获取Helm Releases失败: " + e2.getMessage());
                throw e2;
            }
        }
    }
}
